package service

import (
	"fitness/internal/dao"
	"fitness/pkg/constant"
	"fitness/pkg/tools"
	"fitness/pkg/utils/R"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type LoginService struct {
	SysUserDao      *dao.SysUserDao
	SysUserRolesDao *dao.SysUserRolesDao
	HandlerError    *tools.HandlerError
}

func NewLoginService(SysUserDao *dao.SysUserDao, SysUserRolesDao *dao.SysUserRolesDao, HandlerError *tools.HandlerError) *LoginService {
	return &LoginService{
		SysUserDao:      SysUserDao,
		SysUserRolesDao: SysUserRolesDao,
		HandlerError:    HandlerError,
	}
}

// CheckPassword 校验密码，并且返回用户与角色信息
func (login *LoginService) CheckPassword(c *gin.Context) {
	password := c.PostForm("password")
	username := c.PostForm("username")
	captchaKey := c.PostForm("captchaKey")
	captchaCode := c.PostForm("captchaCode")
	//校验验证码
	captcha := tools.VerifyCaptcha(captchaKey, captchaCode)
	if !captcha {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  "验证码不正确",
		})
		return
	}
	info, err := login.SysUserDao.FindSysUserByUserName(username)
	if err != nil || info.UserName == nil || info.Password == nil {
		login.HandlerError.CheckError(err)
		c.JSON(http.StatusOK, R.ReturnFailMsg("用户名或密码不正确"))
		return
	}
	//比较密码
	err = bcrypt.CompareHashAndPassword([]byte(*info.Password), []byte(password))
	if err != nil {
		login.HandlerError.CheckError(err)
		c.JSON(http.StatusOK, R.ReturnFailMsg("用户名或密码不正确"))
		return
	}
	if *info.Status == constant.Disable {
		c.JSON(http.StatusOK, R.ReturnFailMsg("您的账号已经被禁用，无法登录"))
		return
	}
	//来似创建用户token
	userinfo := make(map[string]any)
	userinfo[constant.UserInfo] = info
	userinfo[constant.NikeName] = info.NickName
	userinfo[constant.UserName] = info.UserName
	userinfo[constant.UserId] = info.ID
	userinfo[constant.UserType] = info.UserType
	userinfo[constant.Avatar] = info.Avatar
	var roleIdStr string
	var roleIds []string
	uRole := login.SysUserRolesDao.FindRoleByUserId(info.ID)
	for _, role := range uRole {
		roleIds = append(roleIds, strconv.FormatUint(*role.RoleId, 10))
	}
	if len(roleIds) > 0 {
		roleIdStr = strings.Join(roleIds, ",")
	}
	userinfo["role_id"] = roleIdStr
	userinfo["create_time"] = time.Now().Unix()

	token, _ := tools.MakeToken(userinfo)
	userinfo["ref_token"] = true
	//创建token
	refToken, _ := tools.MakeToken(userinfo)
	c.JSON(http.StatusOK, R.ReturnSuccessMsgData("验证成功,正在跳转", gin.H{
		"accessToken":  token,
		"refreshToken": refToken,
		"tokenType":    "Bearer",
		"expires":      nil,
		"create_time":  userinfo["create_time"],
	}))
}

func (login *LoginService) Logout(c *gin.Context) {
	c.JSON(http.StatusOK, R.ReturnSuccess("退出成功"))
}
